(function(angular) {
	"use strict";
	angular.module("fs.waf").controller("cls.settlement.initController", initController);
	initController.$inject = [ "$scope", "$q", "clsConstants", "modalService", "gridService", "layoutConfig", "validatorConfig", "authService", "settlementInitService", "setlDetailEventService",
			"payDetailEventService", "payDetailService", "setlDetailService" ];
	function initController($scope, $q, clsConstants, modalService, gridService, layoutConfig, validatorConfig, authService, settlementInitService, setlDetailEventService, payDetailEventService,
			payDetailService, setlDetailService) {
		var ctrl = this, params = $scope.$stateParams.params, errorMessage = {}, settlement = {};
		ctrl.validatorConfig = validatorConfig;
		ctrl.init = function() {
			// 1. init settlement instruction table layout
			ctrl.txnSetlInsts = gridService.createInnerGridOptions($scope, layoutConfig.formConfigs.txnSetlInsts.tableConfigs.txnSetlInsts, null);
			ctrl.txnSetlInsts.data = "vm.settlement.txnSetlInsts";
			// 2. init paydetail table layout
			ctrl.payDetailConfig = gridService.createInnerGridOptions($scope, layoutConfig.formConfigs.payDetailTable.tableConfigs.payDetails, function(eventRow, selectedRows) {
				ctrl.selectedPayDetails = selectedRows;
			});
			ctrl.payDetailConfig.data = "vm.settlement.payDetails";
			// add sub data validator
			if (ctrl.validatorConfig)
				layoutConfig.formConfigs.payDetailTable.tableConfigs.payDetails.validatorConfig = ctrl.validatorConfig.payDetails;
			// prepared settlement init options
			settlementInitService.settlementInitData().then(function(map) {
				return $q(function(resolved, rejected) {
					settlement.gccyOptions = angular.copy(map.ccyOptions);
					settlement.payCcyOptions = map.ccyOptions;
					settlement.fxRates = map.fxRateList;
					settlement.payCodeList = map.payCodeList;
					settlement.allocCodeOptions = map.allocationOptions;
					settlement.fxRateTypeOptions = map.cdaFxRateTypeOptions;
					ctrl.communityIdOptions = map.communityId;
					resolved();
				});
			}).then(function() {
				return $q(function(resolved, rejected) {
					authService.init(params).then(function(response) {
						// init layout data eg:options
						settlement = angular.extend(settlement, response.data.model);
						settlement.taskId = response.data.task.taskId || params.taskId;
						settlement.payDetails = settlement.payDetails || [];
						settlement.setlDetails = settlement.setlDetails || [];
						settlementInitService.initSettlement(settlement);
						resolved(response);
					}, submitFailed);
				});
			}).then(function(response) {
				settlementInitService.getLayout(settlement, "init").then(function(layout) {
					settlementInitService.processDynaparmConfig(settlement.settlementInfo, layout);
					layoutConfig = layout || layoutConfig;
					// set general page
					ctrl.generalConfig = settlementInitService.getGeneralConfig(settlement.settlementInfo, layoutConfig);
					// flash setlDetail page
					setlDetailService.flashSetlDetailsConfig(settlement, layoutConfig);
					ctrl.layoutConfig = layoutConfig;
					settlement.layoutConfigCache = layoutConfig;
					ctrl.setlDetailsPayConfig = layoutConfig.formConfigs.setlDetailTable.tableConfigs.setlDetails.columnDefs;
					ctrl.setlDetailsPayConfig[0].appScope = $scope;
					ctrl.setlDetailsPayConfig[1].appScope = $scope;
					ctrl.setlDetailsPayConfig[8].appScope = $scope;
					ctrl.setlDetailsPayConfig[9].appScope = $scope;
					ctrl.setlDetailsPayConfig[10].appScope = $scope;
					ctrl.settlement = settlement;
					// pay code charge fee
					setlDetailService.updateSetDetailByFee(ctrl.settlement);
					payDetailService.deleteInvalidPayDetail(ctrl.settlement);
					displayWfInfo(response);
				});
			});
		};

		function displayWfInfo(response) {
			var messages = [];
			if (response.data.task.taskProps.wfInfo) {
				var msg = new Object();
				msg.args = response.data.task.taskProps.wfInfo.msgParams || "";
				msg.msg = response.data.task.taskProps.wfInfo.msgCode || "cls.error.unknow.exception";
				messages.push(msg);
			}
			if (messages.length > 0) {
				modalService.openErrorDialogs({
					"messages" : messages
				});
			}
		}

		ctrl.paycodeChanged = function(item, formCtrl, isInitialized) {
			if (isInitialized) {
				return;
			}
			payDetailEventService.paycodeChanged(ctrl.settlement, item, null, false);
			payDetailService.deleteInvalidPayDetail(ctrl.settlement);
		};

		ctrl.acctlookupView = function(payDetail) {
			payDetailEventService.acctlookupView(payDetail);
		};

		ctrl.splitPayDetail = function(payDetail) {
			payDetailEventService.splitPayDetail(ctrl.settlement, payDetail);
			payDetail.splitPayDetail_Show = payDetailService.isShowSplitPayDetail(ctrl.settlement, payDetail);
			payDetailService.deleteInvalidPayDetail(ctrl.settlement);
		};

		ctrl.itemWaiveFlagChanged = function(item, formCtrl, isInitialized) {
			if (isInitialized) {
				return;
			}
			setlDetailEventService.itemWaiveFlagChanged(ctrl.settlement, item);
			payDetailService.deleteInvalidPayDetail(ctrl.settlement);
		};

		ctrl.itemHoldFlagChanged = function(item, formCtrl, isInitialized) {
			if (isInitialized) {
				return;
			}
			setlDetailEventService.itemHoldFlagChanged(ctrl.settlement, item);
			payDetailService.deleteInvalidPayDetail(ctrl.settlement);
		};

		ctrl.taxWaiveFlagChanged = function(item, formCtrl, isInitialized) {
			if (isInitialized) {
				return;
			}
			setlDetailEventService.taxWaiveFlagChanged(ctrl.settlement, item);
			payDetailService.deleteInvalidPayDetail(ctrl.settlement);
		};

		ctrl.itemTransferFlagChanged = function(item, formCtrl, isInitialized) {
			if (isInitialized) {
				return;
			}
			setlDetailEventService.itemTransferFlagChanged(ctrl.settlement, item);
			payDetailService.deleteInvalidPayDetail(ctrl.settlement);
		};

		ctrl.itemCarryoverFlagChanged = function(setlDetail, formCtrl, isInitialized) {
			if (isInitialized) {
				return;
			}
			setlDetailEventService.itemCarryoverFlagChanged(ctrl.settlement, setlDetail);
			payDetailService.deleteInvalidPayDetail(ctrl.settlement);
		};

		ctrl.payCcyChanged = function(item, formCtrl, isInitialized) {
			if (isInitialized) {
				return;
			}
			setlDetailEventService.payCcyChanged(ctrl.settlement, item);
			payDetailService.deleteInvalidPayDetail(ctrl.settlement);
		};

		ctrl.fxCrossRateFlagChanged = function(item, formCtrl, isInitialized) {
			if (isInitialized) {
				return;
			}
			setlDetailEventService.fxCrossRateFlagChanged(ctrl.settlement, item);
			payDetailService.deleteInvalidPayDetail(ctrl.settlement);
		};

		ctrl.splitbox = function(item) {
			setlDetailEventService.splitbox(ctrl.settlement, item);
			payDetailService.deleteInvalidPayDetail(ctrl.settlement);
		};

		ctrl.changefxRateType1 = function(item, formCtrl, isInitialized) {
			if (isInitialized) {
				return;
			}
			setlDetailEventService.changefxRateType(ctrl.settlement, item, "fxr1");
			payDetailService.deleteInvalidPayDetail(ctrl.settlement);
		};

		ctrl.changefxRateType2 = function(item, formCtrl, isInitialized) {
			if (isInitialized) {
				return;
			}
			setlDetailEventService.changefxRateType(ctrl.settlement, item, "fxr2");
			payDetailService.deleteInvalidPayDetail(ctrl.settlement);
		};

		ctrl.fxCrossRateChanged = function(item, formCtrl, isInitialized) {
			if (isInitialized) {
				return;
			}
			setlDetailEventService.fxCrossRateChanged(ctrl.settlement, item);
			payDetailService.deleteInvalidPayDetail(ctrl.settlement);
		};

		ctrl.deleteItem = function(item) {
			setlDetailEventService.deleteSetlDetail(ctrl.settlement, item);
			payDetailService.deleteInvalidPayDetail(ctrl.settlement);
		};

		ctrl.createNew = function(item) {
			// TODO
			setlDetailEventService.getFxCrossRate(ctrl.settlement, item);
		};

		ctrl.allocCodeChanged = function(item, formCtrl, isInitialized) {
//			if (isInitialized) {
//				return;
//			}
			setlDetailEventService.allocCodeChanged(ctrl.settlement, item);
			payDetailService.deleteInvalidPayDetail(ctrl.settlement);
		};

		ctrl.payDetailAllocCodeChanged = function(payDetail, formCtrl, isInitialized) {
			if (isInitialized) {
				return;
			}
			if (payDetail.custAcctFlag == "Y") {
				payDetail.acctNo = "";
			}
		};

		ctrl.paydetailSeqChanged = function(setlDetail, formCtrl, isInitialized) {
			if (isInitialized) {
				return;
			}
			setlDetailEventService.paydetailSeqChanged(ctrl.settlement, setlDetail);
			payDetailService.deleteInvalidPayDetail(ctrl.settlement);
		};

		ctrl.addFeeboxCr = function() {
			setlDetailEventService.feebox("addcr", ctrl.settlement);
			payDetailService.deleteInvalidPayDetail(ctrl.settlement);
		};

		ctrl.addFeeboxDr = function() {
			setlDetailEventService.feebox("adddr", ctrl.settlement);
			payDetailService.deleteInvalidPayDetail(ctrl.settlement);
		};

		ctrl.changeAmountBox = function(item) {
			setlDetailEventService.changeAmountBox(ctrl.settlement, item);
			payDetailService.deleteInvalidPayDetail(ctrl.settlement);
		};

		ctrl.isDetailsPay = function(item) {
			if (item.crDrFlag == "C" && item.itemSubtype != clsConstants.SetlDetailItemSubType.INTEREST_NO_REFUND) {
				return true;
			}
			return false;
		};

		ctrl.isDetailsReceive = function(item) {
			if (item.crDrFlag == "D" && item.itemSubtype != clsConstants.SetlDetailItemSubType.INTEREST_NO_REFUND) {
				return true;
			}
			return false;
		};

		ctrl.isShowSplit = function(item) {
			if (item.feeNewFlag == "N" && item.isShowSplit != null) {
				return item.isShowSplit;
			}
			if (item.itemType == "F" && item.feeNewFlag == "N" && item.childFlag == "N"
			// && ctrl.settlement.paymentType != "C"
			) {
				return true;
			}
			if (item.itemType != "F" && item.childFlag == "N"
			// && ctrl.settlement.paymentType != "C"
			&& !(item.itemType == "P" && setlDetailService.isRolloverRemittance(item.itemSubtype))) {
				return true;
			}
			return false;
		};

		ctrl.isShowDeleteItem = function(item) {
			if (item.itemType == "F" && item.feeNewFlag == "Y") {
				return true;
			}
			return false;
		};

		ctrl.isShowPaydetailSeq = function(item) {
			if (item.itemHoldFlag == "Y" || item.itemWaiveFlag == "Y") {
				return false;
			} else {
				return true;
			}
		};

		ctrl.isShowAmountItem = function(item) {
			if (ctrl.isShowPaydetailSeq(item) && item.itemType == "F" && item.childFlag == "N") {
				return true;
			}
			return false;
		};
		
		ctrl.settlementLoanIdLink = function(settlement){
			modalService.openCustomDialogs({
				"title" : "popup.title.loanview",
				"dialogsModule" : "cls.loan.view",
				"params" : {"loanId" : settlement.loan.loanInfo.loanId},
				"size" : [1300, 500],
				"btnCallback" : {
					"ok" : function(obj) {
					}
				}
			});
		};
		
		ctrl.settlementCustpayIdLink = function(settlement){
			modalService.openCustomDialogs({
				"title" : "popup.title.custpayview",
				"dialogsModule" : "cls.custpay.view",
				"params" : {"custpayId" : settlement.custpay.custpayId},
				"size" : [1300, 500],
				"btnCallback" : {
					"ok" : function(obj) {
					}
				}
			});
		};
		
		ctrl.settlementRepayIdLink = function(settlement){
			modalService.openCustomDialogs({
				"title" : "popup.title.repaymentview",
				"dialogsModule" : "cls.loan.repaymentView",
				"params" : {"repayId" : settlement.payment.repayId},
				"size" : [1300, 500],
				"btnCallback" : {
					"ok" : function(obj) {
					}
				}
			});
		};
		
		ctrl.settlementDchargeIdLink = function(settlement){
			modalService.openCustomDialogs({
				"title" : "popup.title.dchargeview",
				"dialogsModule" : "cls.dcharge.view",
				"params" : {"dchargeId" : settlement.dcharge.dchargeId},
				"size" : [1300, 500],
				"btnCallback" : {
					"ok" : function(obj) {
					}
				}
			});
		};

		ctrl.next = function() {
			var messages = [];
			angular.forEach(errorMessage, function(field) {
				angular.forEach(field, function(rule) {
					messages.push(rule);
				});
			});
			if (messages.length > 0) {
				modalService.openErrorDialogs({
					"messages" : messages
				});
			} else {
				return authService.next(getSettlementInfo(ctrl.settlement)).then(submitSuccessful, submitFailed);
			}
		};

		function getSettlementInfo(settlement) {
			var settlement_new = {};
			angular.forEach(settlement, function(data, attribute) {
				if (attribute != "setlDetailCache" && attribute != "setlDetails" && attribute != "layoutConfigCache") {
					settlement_new[attribute] = angular.copy(data);
				} else if (attribute == "setlDetails") {
					settlement_new[attribute] = getSetlDetails(data);
				}
			});
			return settlement_new;
		}

		function getSetlDetails(setlDetails) {
			var setlDetails_new = [];
			angular.forEach(setlDetails, function(setlDetail) {
				var setlDetail_new = {};
				angular.forEach(setlDetail, function(data, attribute) {
					if (attribute != "setlDetailConfig") {
						setlDetail_new[attribute] = angular.copy(data);
					}
				});
				setlDetails_new.push(setlDetail_new);
			});
			return setlDetails_new;
		}

		ctrl.back = function() {
			var messages = [];
			angular.forEach(errorMessage, function(field) {
				angular.forEach(field, function(rule) {
					messages.push(rule);
				});
			});
			if (messages.length > 0) {
				modalService.openErrorDialogs({
					"messages" : messages
				});
			} else {
				modalService.openJumpDialogs({
					"messages" : [ "title.dialog.settlementinit.back" ],
					"btnCallback" : {
						"close" : function() {
						}
					},
					"redirections" : [ {
						"name" : getBackMessage(ctrl.settlement.settlementInfo),
						"jump" : function() {
							authService.back(getSettlementInfo(ctrl.settlement)).then(submitSuccessful, submitFailed);
						}
					}, {
						"name" : "title.infobar.workflow.list",
						"state" : "cls.workflow.wfTxn.list",
						"params" : {}
					} ]
				});
			}
		};

		function getBackMessage(settlementInfo) {
			return settlementInitService.getBackMessage(settlementInfo);
		}

		function submitSuccessful(response) {
			modalService.openAcknowledgeDialogs({
				"messages" : [ "title.dialog.successful.submit" ],
				"btnCallback" : {
					"close" : function() {
						$scope.go("cls.workflow.wfTxn.list");
					}
				},
				"redirections" : [ {
					"name" : "title.infobar.workflow.list",
					"state" : "cls.workflow.wfTxn.list",
					"params" : {}
				} ]
			});
		}

		$scope.$watch("vm.settlement.payDetails", function(payDetails) {
			if (payDetails) {
				payDetailEventService.setPaydetailCompanyCode(ctrl.settlement);
			}
		}, true);

		function submitFailed(response) {
			modalService.openErrorDialogs({
				"messages" : response.error
			});
		}

	}
})(angular);
